package com.hskn.hss.utils.PerformanceMonitor;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 性能统计
 * @author faith.huan
 */
public class PerformanceMonitor {
	// 使用自己的logger,用于预警识别
	public static final Logger logger = LoggerFactory.getLogger(PerformanceMonitor.class);

	private static ThreadLocal<MethodPerformance> performanceRecord = new ThreadLocal<MethodPerformance>();

	public static void begin(String method) {
		logger.info("PerformanceMonitor->begin monitor {}", method);
		MethodPerformance mp = new MethodPerformance(method);
		performanceRecord.set(mp);
	}
	
	/**
	 * 开始统计点
	 * @param method
	 * @param isInfo  标识是否输出开始统计日志
	 * @author faith.huan@2018年2月2日 上午10:15:05
	 */
	public static void begin(String method, boolean isInfo) {
		if (isInfo) {
			logger.info("PerformanceMonitor->begin monitor {}", method);
		}
		MethodPerformance mp = new MethodPerformance(method);
		performanceRecord.set(mp);
	}

	public static void end() {
		MethodPerformance mp = performanceRecord.get();
		logger.info("PerformanceMonitor->end monitor {}", mp.getServiceMethod());
		mp.printPerformance(logger);
	}
	
	/**
	 * 时间小于min的不输出耗时日志
	 * @param min
	 * @author faith.huan@2018年2月2日 上午10:17:43
	 */
	public static void end(int min) {
		MethodPerformance mp = performanceRecord.get();
		logger.info("PerformanceMonitor->end monitor {}", mp.getServiceMethod());
		mp.printPerformance(min, logger);
	}

	public static void end(int min, boolean isInfo) {
		MethodPerformance mp = performanceRecord.get();
		if (isInfo) {
			logger.info("PerformanceMonitor->end monitor {}", mp.getServiceMethod());
		}
		mp.printPerformance(min, logger);
	}
}

class MethodPerformance {
	private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	private Date begin;
	private Date end;
	private String serviceMethod;

	public MethodPerformance(String serviceMethod) {
		this.begin = new Date();
		this.serviceMethod = serviceMethod;
	}

	public void printPerformance(Logger logger) {
		end = new Date();
		long consum = end.getTime() - begin.getTime();
		if (consum > 100L) {
			logger.info("PerformanceMonitor->{}花费{}毫秒.{}->{}", serviceMethod, consum, formatter.format(begin), formatter.format(end));

		}
	}
	public void printPerformance(int min, Logger logger) {
		end = new Date();
		long consum = end.getTime()-begin.getTime();
		if (consum > min) {
			logger.info("PerformanceMonitor->{}花费{}毫秒.{}->{}", serviceMethod, consum, formatter.format(begin), formatter.format(end));
		}
	}

	public String getServiceMethod() {
		return serviceMethod;
	}

}
